import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";


var w = window.innerWidth
var h = window.innerHeight
var scene, camera, renderer, vertices = [], colors = [], light
const LEN = 16000,  SIZE = 6
var SCOPE = 180

function main() {
  init()
  setLine()
  setLight()
  render()
}

function init() {
  // 创建场景对象Scene
  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(75, w / h, 1, 1000)
  camera.position.x = 0
  camera.position.y = 0
  camera.position.z = 320
  camera.up.x = 0
  camera.up.y = 1
  camera.up.z = 0
  camera.lookAt({ x: 0, y: 0, z: 0 })

  renderer = new THREE.WebGLRenderer()
  renderer.setClearColor('#8edee2')
  renderer.setSize(w, h)
  document.body.appendChild(renderer.domElement)
}

function setLine() {
  var geometry = new THREE.BufferGeometry()
  var n = SCOPE/2
  var c = []
  for (let j = 0; j < 11; j++) {
    c.push(j/10)
  }
  for (let i = 0; i < LEN; i++) {
    var x = Math.random() * SCOPE - n
    var y = Math.random() * SCOPE - n
    var z = Math.random() * SCOPE - n
    
    vertices.push(
      x + Math.random() * SIZE,
      y + Math.random() * SIZE,
      z + Math.random() * SIZE,
      x + Math.random() * SIZE,
      y + Math.random() * SIZE,
      z + Math.random() * SIZE,
      x + Math.random() * SIZE,
      y + Math.random() * SIZE,
      z + Math.random() * SIZE,
    )
  //  var r = x>0?1:0
  //  var g = y>0?1:0
  //  var b = z>0?1:0
   var r = c[Math.floor(x/18+5)]
   var g = c[Math.floor(y/18+5)]
   var b = c[Math.floor(z/18+5)]
  //  console.log('====',r,g,b);
   
    colors.push(
      r,g,b,Math.random(),
      r,g,b,Math.random(),
      r,g,b,Math.random(),
    )
  }
  console.log('colors', colors);


  geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3))
  geometry.setAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 4))

  var material = new THREE.LineBasicMaterial({
    side: THREE.DoubleSide,
    vertexColors: THREE.VertexColors, 
  });
  var mesh = new THREE.Mesh(geometry, material)
  scene.add(mesh)
}

function setLight() {
  var light2 = new THREE.DirectionalLight(0xffff00, 0.6)
  light2.position.set(0, 0, -800)
  scene.add(light2)

  light = new THREE.DirectionalLight(0xffff00, 0.7, 1000, 1)
  light.position.set(0, 0, 800)
  scene.add(light)
}
function render() {
  renderer.render(scene, camera)
}

main()
/** --------------------鼠标控件对象--------------------- */
let controls = new OrbitControls(camera, renderer.domElement); //创建控件对象
controls.addEventListener("change", render); //监听鼠标、键盘事件